package cn.sjx.print.service.customer.impl;

import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import cn.sjx.print.constants.PrintConstant;
import cn.sjx.print.service.customer.JasperReportRenderHtmlHandler;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

/**
 * JasperReport生成html默认实现
 *
 * @author sjx
 * @date 2020年11月25日 10:13:08
 */
public class JasperReportRenderHtmlHandlerDefaultImpl implements JasperReportRenderHtmlHandler {

    @Override
    public String handle(String htmlStr) {
        Document document = Jsoup.parse(htmlStr);
        Elements selects = document.select(".jrPage");
        /*
        // 方法1：
        for (Element select : selects) {
            String style = selects.attr("style");
            if (StrUtil.isNotBlank(style)) {
                select.attr("style",
                        ReUtil.replaceAll(style, RE_STYLE_WIDTH, "width: 700px;"));
            }
        }
        */

        // 方法2：
        for (Element select : selects) {
            // 删除左右50%宽度标签
            String style = selects.attr("style");
            if (StrUtil.isNotBlank(style)) {
                select.attr("style",
                        ReUtil.replaceAll(style, PrintConstant.RE_STYLE_WIDTH, "width: 100%;") + "table-layout: fixed;");
            }

            // 删除tr的上下间距,让其自适应
            /*
            if (PrintConstant.PRINT_CONFIG_SETTING.getBool(PrintConstant.PRINT_CONFIG_PRINT_RENDER_HTML_TR_STYLE_REMOVE)) {
                Elements tagTrs = selects.select("tr:not(:last-child)");
                if (CollUtil.isNotEmpty(tagTrs)) {
                    for (int i = 0; i < tagTrs.size(); i++) {
                        // 过滤前三条
                        if (i < 3) {
                            continue;
                        }
                        tagTrs.get(i).removeAttr("style");
                    }
                }
            }
            */
        }

        document.selectFirst("table").selectFirst("td").remove();
        document.selectFirst("table").select("td:last-child").last().remove();

        return document.html()
                // 单引号转义
                .replaceAll("\'", "\\\\'")
                // 去除换行符
                .replaceAll("\\n", "");
    }

}
